package cmd

import (
	"errors"
	"os"

	"gitee.com/eeppee_admin/go-tuiftp/internal/service/config"
	"gitee.com/eeppee_admin/go-tuiftp/reuse"

	"github.com/spf13/cobra"
)

// 配置命令
type ConfigCommand struct {
	cmd *cobra.Command
}

func NewConfigCommand() *cobra.Command {
	c := new(ConfigCommand)
	c.cmd = &cobra.Command{
		Use:   "config",
		Short: "config ftp site infomation | 配置ftp站点信息",
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) == 0 {
				config.List()
				os.Exit(0)
			}
		},
	}
	c.create()
	c.edit()
	c.list()
	c.delete()

	return c.cmd
}

// config子命令create
func (c *ConfigCommand) create() {
	var siteCfg reuse.SiteConfig

	ccmd := &cobra.Command{
		Use:   "create",
		Short: "create ftp site config",
		Run: func(cmd *cobra.Command, args []string) {
			config.Create(&siteCfg)
		},
	}

	ccmd.Flags().StringVarP(&siteCfg.Name, "name", "n", "", "ftp site name")
	// todo: add support for ftp, sftp, ftps
	ccmd.Flags().StringVarP(&siteCfg.Type, "type", "t", "ftp", "ftp site type")
	// h is already take as help
	ccmd.Flags().StringVarP(&siteCfg.Host, "host", "H", "", "ftp site host")
	// port can be string, then parse as int
	ccmd.Flags().StringVarP(&siteCfg.Port, "port", "P", "21", "ftp site port")
	ccmd.Flags().StringVarP(&siteCfg.Account, "account", "a", "", "ftp site account")
	ccmd.Flags().StringVarP(&siteCfg.Password, "password", "p", "", "ftp site password")

	c.cmd.AddCommand(ccmd)
}

func (c *ConfigCommand) edit() {
	var siteName string

	ccmd := &cobra.Command{
		Use:   "edit",
		Short: "edit ftp site config",
		// 添加参数验证
		PreRunE: func(cmd *cobra.Command, args []string) error {
			if siteName == "" {
				return errors.New("请使用 -n 或 --name 指定要编辑的站点名称")
			}
			return nil
		},
		Run: func(cmd *cobra.Command, args []string) {
			config.Edit(siteName)
		},
	}

	// 标记name为必需参数
	ccmd.Flags().StringVarP(&siteName, "name", "n", "", "ftp site name (required)")
	ccmd.MarkFlagRequired("name") // 标记为必需参数

	c.cmd.AddCommand(ccmd)
}

func (c *ConfigCommand) delete() {
	var siteName string

	ccmd := &cobra.Command{
		Use:   "delete",
		Short: "delete ftp site config",
		// 添加参数验证
		PreRunE: func(cmd *cobra.Command, args []string) error {
			if siteName == "" {
				return errors.New("请使用 -n 或 --name 指定要删除的站点名称")
			}
			return nil
		},
		Run: func(cmd *cobra.Command, args []string) {
			config.Delete(siteName)
		},
	}

	// 标记name为必需参数
	ccmd.Flags().StringVarP(&siteName, "name", "n", "", "ftp site name (required)")
	ccmd.MarkFlagRequired("name") // 标记为必需参数

	c.cmd.AddCommand(ccmd)
}

func (c *ConfigCommand) list() {
	ccmd := &cobra.Command{
		Use:   "list",
		Short: "list ftp site config",
		Run: func(cmd *cobra.Command, args []string) {
			config.List()
		},
	}

	c.cmd.AddCommand(ccmd)
}
